<template>
    <div class="border-1 border-solid border-#ccc max-w-100%">
        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
        />
        <Editor
            style="height: 500px; width: 100%; overflow-y: hidden"
            v-model="value"
            :defaultConfig="editorConfig"
            @onCreated="handleCreated"
        />
    </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { inject, shallowRef, onBeforeUnmount } from "vue";
import { IMG_URL } from "../assets/common/config";

const value = defineModel("value");

const $message = inject("$message");
const $axios = inject("$axios");

const editorRef = shallowRef();
const toolbarConfig = {
    excludeKeys: ["fullScreen", "uploadVideo", "fontFamily"],
};
const editorConfig = {
    placeholder: "请输入内容...",
    MENU_CONF: {
        fontFamily: {
            fontFamilyList: [], // 只可用默认字体
        },
        uploadImage: {
            async customUpload(file, insertFn) {
                if (file.size >= 5 * 1024 * 1024) {
                    return $message({
                        message: "请上传小于5M的图片",
                        type: "warning",
                    });
                }
                let data = new FormData();
                const name = file.uid + "." + file.name.split(".")[1];
                const renamedFile = new File([file], name);
                data.append("file", renamedFile);
                $axios.post("resources/public", data).then((res) => {
                    if (res.data.code === 200) {
                        const url = IMG_URL + res.data.data.url;
                        insertFn(url, renamedFile.name, url);
                    } else {
                        $message({ message: res.data.msg, type: "error" });
                    }
                });
            },
        },
    },
};

onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>
